import {
  defineStore
} from "pinia";
import {
  computed,
  ref
} from "vue";

import {
  getCart,
  insertCart,
  delCartAPI,
  mergeCartAPI
} from '@/apis/cart'
import {
  useUserStore
} from "./user";
export const useCartStore = defineStore('cart', () => {
  //判断是否登录
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])
  //清空购物车
  const clearCart = () => {
    cartList.value = []
  }
  //获取最新购物车
  const getNewCart = async () => {
    const res = await getCart()
    cartList.value = res.result
  }
  //购物车添加商品
  const addCart = async (goods) => {
    if (isLogin.value) {
      await insertCart(goods.skuId, goods.count)
      getNewCart()
    } else {
      //添加商品逻辑
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        item.count += goods.count
      } else {
        cartList.value.push(goods)
      }
    }

  }
  //购物车删除商品
  const delCart = async (Index) => {
    if (isLogin.value) {
      await delCartAPI([cartList.value[Index].skuId])
      getNewCart()
    } else cartList.value.splice(Index, 1)

  }
  //购物车总数计算
  const allCount = computed(() => cartList.value.reduce((accumulator, currentValue) =>
    accumulator + currentValue.count, 0))
  //购物车总价格计算
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  //单选框逻辑
  const singleCheck = (item, selected) => {
    const e = cartList.value.find((i) => item.skuId === i.skuId)
    e.selected = selected
  }
  //合并购物车逻辑
  const mergeCart = async () => {
    await mergeCartAPI(cartList.value.map((item) => {
      return{
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
  }
  //是否全选判断
  const isAll = computed(() => cartList.value.every(item => item.selected))
  //购物车全选逻辑
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }
  //选中总数
  const checkCount = computed(() => cartList.value.filter(item => item.selected).reduce((a,
    c) => a + c.count, 0))
  //总消费
  const allUse = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) =>
    a + c.count * c.price, 0))
  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    isAll,
    allCheck,
    checkCount,
    allUse,
    clearCart,
    mergeCart,
    getNewCart
  }
}, {
  persist: true,
}, )
